package com.example.emos.api.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.json.JSONUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.common.util.R;
import com.example.emos.api.controller.form.*;
import com.example.emos.api.db.pojo.TbDept;
import com.example.emos.api.service.DeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/dept")
@Tag(name = "DeptController", description = "部门Web接口")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @PostMapping("/delete")
    @SaCheckPermission(value = {"ROOT","DEPT:DELETE"},mode = SaMode.OR)
    @Operation(summary = "修改部门")
    public R deleteeDept(@Valid @RequestBody DeleteUserForm form) {
        int rows = this.deptService.delete(form.getIds());

        return R.ok().put("rows",rows);
    }

    @PostMapping("/update")
    @SaCheckPermission(value = {"ROOT","DEPT:UPDATE"},mode = SaMode.OR)
    @Operation(summary = "修改部门")
    public R updateDept(@Valid @RequestBody DeptUpdateForm form) {
        TbDept tbDept = JSONUtil.parse(form).toBean(TbDept.class);

        int rows = this.deptService.update(tbDept);
        return R.ok().put("rows",rows);
    }

    @PostMapping("/insert")
    @SaCheckPermission(value = {"ROOT","DEPT:INSERT"},mode = SaMode.OR)
    @Operation(summary = "新增部门")
    public R addDept(@Valid @RequestBody DeptAddForm form) {
        TbDept tbDept = JSONUtil.parse(form).toBean(TbDept.class);

        int rows = this.deptService.insert(tbDept);
        return R.ok().put("rows",rows);
    }

    @PostMapping("/searchPageDept")
    @SaCheckPermission(value = {"ROOT","DEPT:SELECT"},mode = SaMode.OR)
    @Operation(summary = "分页查询部门")
    public R selectDeptPage(@Valid @RequestBody DeptSearchFrom from) {
        from.setPage((from.getPage() - 1) * from.getLength());
        HashMap hashMap = JSONUtil.parse(from).toBean(HashMap.class);
        hashMap.put("start", from.getPage());
        PageUtils pageUtils = this.deptService.selectDeptPage(hashMap);
        return R.ok().put("page", pageUtils);
    }

    @GetMapping("/searchAllDept")
    @Operation(summary = "查询所有部门")
    public R searchAllDept() {
        ArrayList<HashMap> list = deptService.searchAllDept();
        return R.ok().put("list", list);
    }

    @PostMapping("/searchById")
    @Operation(summary = "根据ID查询部门")
    @SaCheckPermission(value = {"ROOT", "DEPT:SELECT"}, mode = SaMode.OR)
    public R searchById(@Valid @RequestBody SearchDeptByIdForm form) {
        HashMap map = deptService.searchById(form.getId());
        return R.ok(map);
    }

}
